package gzh.controller;

import gzh.component.WebSocketServer;
import gzh.repository.ForbiddenWordRepository;
import gzh.vo.ForbiddenWord;
import gzh.vo.Message;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;

@RestController
@RequestMapping("/api")
public class ForbiddenWordController {

    @Autowired
    private ForbiddenWordRepository forbiddenWordRepository;

    private static final AtomicLong ID_GENERATOR = new AtomicLong(1L);

    @GetMapping("/forbidden-words")
    public List<ForbiddenWord> getAll() {
        return forbiddenWordRepository.findAll();
    }

    private static class AddForbiddenWordRequest {
        private String word;

        public String getWord() {
            return word;
        }

        public void setWord(String word) {
            this.word = word;
        }
    }

    @PostMapping("/forbidden-words")
    public ForbiddenWord add(@RequestBody AddForbiddenWordRequest request) {
        if (request == null || request.getWord() == null || request.getWord().trim().isEmpty()) {
            throw new IllegalArgumentException("违禁词不能为空");
        }

        ForbiddenWord newWord = new ForbiddenWord();
        newWord.setId(ID_GENERATOR.getAndIncrement());
        newWord.setWord(request.getWord().trim());
        newWord.setCreateTime(new Date());

        forbiddenWordRepository.save(newWord);
        sendForbiddenWordsUpdate();
        return newWord;
    }

    @DeleteMapping("/forbidden-words/{id}")
    public void delete(@PathVariable Long id) {
        forbiddenWordRepository.deleteById(id);
        sendForbiddenWordsUpdate();
    }

    private void sendForbiddenWordsUpdate() {
        List<ForbiddenWord> allWords = forbiddenWordRepository.findAll();
        List<String> words = new ArrayList<>();
        for (ForbiddenWord word : allWords) {
            words.add(word.getWord());
        }

        Message systemMsg = new Message();
        systemMsg.setSystemMessage(true);
        systemMsg.setUserNames(words);

        WebSocketServer.sendAllMessage(JSON.toJSONString(systemMsg));
    }
}